package io.qytc.jboot.controller;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.interceptor.POST;
import io.jboot.components.rpc.annotation.RPCInject;
import io.jboot.web.controller.annotation.RequestMapping;
import io.qytc.jboot.base.common.Consts;
import io.qytc.jboot.base.common.RestResult;
import io.qytc.jboot.base.plugin.shiro.MuitiLoginToken;
import io.qytc.jboot.base.web.base.BaseController;
import io.qytc.jboot.entity.License;
import io.qytc.jboot.service.api.UserService;
import io.qytc.jboot.service.api.VersionInfoService;
import io.qytc.jboot.service.entity.model.User;
import io.qytc.jboot.service.entity.model.VersionInfo;
import io.qytc.jboot.support.auth.LicensesInterceptor;
import io.qytc.jboot.utils.LicenseUtils;
import io.qytc.jboot.validator.LoginValidator;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;

import java.util.HashMap;
import java.util.List;

/**
 * 主控制器
 * @author Rlax
 *
 */
@RequestMapping("/")
public class MainController extends BaseController {

    @RPCInject
    private UserService userService;

    @RPCInject
    private VersionInfoService versionInfoService;

    @Clear(LicensesInterceptor.class)
    public void index() {
        render("index.html");
    }

    @Clear(LicensesInterceptor.class)
    public void login() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            redirect("/");
        } else {
            render("login.html");
        }
    }

    @Clear(LicensesInterceptor.class)
    public void login1() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            redirect("/");
        } else {
            renderJson(RestResult.buildError("没有登录"));
        }
    }

    @Clear(LicensesInterceptor.class)
    public void captcha() {
        renderCaptcha();
    }

    @Clear(LicensesInterceptor.class)
    @Before( {POST.class, LoginValidator.class} )
    public void postLogin() {
        String loginName = getPara("loginName");
        String pwd = getPara("password");

        MuitiLoginToken token = new MuitiLoginToken(loginName, pwd);
        Subject subject = SecurityUtils.getSubject();

        RestResult<String> restResult = new RestResult<String>();
        restResult.success().setMsg("登录成功");

        try {
            if (!subject.isAuthenticated()) {
                token.setRememberMe(false);
                subject.login(token);

                User u = userService.findByName(loginName);
                subject.getSession(true).setAttribute(Consts.SESSION_USER, u);
            }
            if (getParaToBoolean("rememberMe") != null && getParaToBoolean("rememberMe")) {
                setCookie("loginName", loginName, 60 * 60 * 24 * 7);
            } else {
                removeCookie("loginName");
            }
        } catch (UnknownAccountException une) {
            restResult.error("用户名不存在");
        } catch (LockedAccountException lae) {
            restResult.error("用户被锁定");
        } catch (IncorrectCredentialsException ine) {
            restResult.error("用户名或密码不正确");
        } catch (ExcessiveAttemptsException exe) {
            restResult.error("账户密码错误次数过多，账户已被限制登录1小时");
        } catch (Exception e) {
            e.printStackTrace();
            restResult.error("服务异常，请稍后重试");
        }

        renderJson(restResult);
    }

    /**
     * 退出
     */
    @Clear(LicensesInterceptor.class)
    public void logout() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            SecurityUtils.getSubject().logout();
        }
        render("login.html");
    }

    public void welcome() {
        // try {
        //     License licenses = LicenseUtils.getLicense();
        //     if (1 == licenses.getPrivilege()){
        //         licenses.setDeadLine("永不过期");
        //     }
        //     setAttr("licenses",licenses);
        // } catch (Exception e) {
        //     e.printStackTrace();
        // }
        List<VersionInfo> versionInfoList = versionInfoService.findAll();
        HashMap<Object, Object> map = new HashMap<>();
        for (VersionInfo v : versionInfoList){
            map.put(v.getName(),v.getValue());
        }
        setAttr("versionInfo",map);
        render("welcome.html");
    }

    @Clear(LicensesInterceptor.class)
    public void licenses() {
        render("licenses.html");
    }

    @Clear(LicensesInterceptor.class)
    public void uploadLicenses(){
        RestResult<String> restResult = new RestResult<String>();
        try {
            if (LicenseUtils.deleteLicense()){
                getFile("","license");
                restResult.success().setMsg("license导入成功！");

            }else {
                restResult.error().setMsg("license导入失败！");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            restResult.error().setMsg("导入时出现异常！");
        }
        renderJson(restResult);
    }

    @Clear(LicensesInterceptor.class)
    public void getSN(){
        RestResult<String> restResult = new RestResult<String>();
        String sn = LicenseUtils.getSN();

        if(sn.equals("")){//如果SN为空，则生成SN，并且重新获取一遍
            LicenseUtils.generateSN();
            sn = LicenseUtils.getSN();
        }

        restResult.success().setMsg(sn);
        renderJson(restResult);
    }

    public void display(){
        render("display.html");
    }

}
